//
// File:	Level.cpp
// Author:	Thomas TISSOT-DUPONT
// E-mail:	<thomas.tissotdupont@free.fr>
// Create:	23/04/2010 16:56:05
// Purpose:	
//
#include "Base.hpp"
#include "Level.hpp"
#include "Trace.hpp"

//------------------------------------------------------------------
// Constructor / Destructor
//------------------------------------------------------------------
Level::Level()
	:	m_parser(),
		m_pLevelRootElement(NULL)
{
}

Level::~Level()
{
}

//------------------------------------------------------------------
// Load Level File
//------------------------------------------------------------------
bool Level::LoadLevelFile(const std::string &fileName)
{
	Clear();
	if (m_parser.ParseFromFile(fileName) == false)
		return false;

	//Level Root
	m_pLevelRootElement = m_parser.GetRootElement().FindChild("level");
	if (m_pLevelRootElement == NULL)
	{
		m_parser.Clear();
		return false;
	}
	return true;
}

//------------------------------------------------------------------
// Create World
//------------------------------------------------------------------
bool Level::CreateWorld() const
{
	//Spawn the world
	Parser::Element *pWorldRootElement = m_pLevelRootElement->FindChild("world");
	if (pWorldRootElement == NULL)
		return false;
	return true;
}


//------------------------------------------------------------------
// Create Entities
//------------------------------------------------------------------
bool Level::CreateEntities() const
{
	//get the entities description from the level file
	Parser::Element *pEntitiesRootElement = m_pLevelRootElement->FindChild("entities");
	if (pEntitiesRootElement == NULL)
		return false;

	//Entity mendatory keys
	std::list<std::string> entityMendatoryKeys;
	entityMendatoryKeys.push_back("classname");

	//Spawn each entity into the world
	const std::list<const Parser::Element *> entities = pEntitiesRootElement->FindChildren("entity");
	std::list<const Parser::Element *>::const_iterator entIt = entities.begin();
	std::list<const Parser::Element *>::const_iterator entIte = entities.end();
	for (; entIt != entIte; ++entIt)
	{
		const Parser::Element *pEntityElement = *entIt;
		if (pEntityElement->HasKeys(entityMendatoryKeys))
		{
			std::map<std::string, Variant> keyvalues = pEntityElement->GetKeyValues();
			if (GlobalVariables::FactoryManager::Get().GetEntityFactory() != NULL)
			{
				IEntity *pEntity = GlobalVariables::FactoryManager::Get().GetEntityFactory()->CreateEntityByName(keyvalues["classname"], &keyvalues);
			}
		}
	}
	return true;
}

//------------------------------------------------------------------
// Clear
//------------------------------------------------------------------
void Level::Clear()
{
	m_parser.Clear();
	m_pLevelRootElement = NULL;
}
